package pri.wallen.waitNotifyModel;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 项目名称：DaemonThreadLab
 * 类名称：WaitNotify
 * 类描述：
 * 创建人：Wallen Han
 * 创建时间：2018年03月19日 18:23
 */
public class WaitNotify {
    static  boolean flag = true;
    static  Object lock = new Object();

    public static void main(String[] args) throws Exception {

        Thread waitThread = new Thread( new Wait(), "WaitThread");
        waitThread.start();
        TimeUnit.SECONDS.sleep(1);
        Thread notifyThread = new Thread( new Notify(), "NotifyThread");
        notifyThread.start();
    }

    static class Wait implements Runnable {

        @Override
        public void run() {
            // 加锁， 拥有 lock 的 Monitor
            synchronized (lock) {
                // 条件不满足时， wait，同时释放 lock 的锁
                while (flag) {
                    try {
                        System.out.println(Thread.currentThread() + " flag is true. wait @ " +
                                new SimpleDateFormat("HH:mm:ss").format(new Date()));
                        lock.wait();
                    } catch ( InterruptedException e){
                        e.printStackTrace();
                    }
                }
                // 满足条件 完成工作
                System.out.println(Thread.currentThread() + " flag is false. Running @ " +
                        new SimpleDateFormat("HH:mm:ss").format(new Date()));
            }
        }
    }

    static  class Notify implements  Runnable {

        @Override
        public void run() {
            synchronized (lock) {
                System.out.println(Thread.currentThread() + " hold lock. notify @ " +
                        new SimpleDateFormat("HH:mm:ss").format(new Date()));
                lock.notifyAll();
                flag = false;
                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            synchronized (lock) {
                System.out.println(Thread.currentThread() + " hold lock again.  sleep @ " +
                        new SimpleDateFormat("HH:mm:ss").format(new Date()));
                try {
                    Thread.sleep(5*1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
